package com.baizhi.controller;

import com.baizhi.entity.Section;
import com.baizhi.service.SectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/section")
public class SectionController {

    @Autowired
    private SectionService sectionService;

    @GetMapping("/sections")
    public Map showAll(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "5") Integer limit,
                       String search){
        Map map = new HashMap();
        System.out.println("search = " + search);
        List<Section> list = sectionService.selectPage(search,page,limit);
        Integer total = sectionService.selectTotalRows(search);
        map.put("count",total);
        map.put("data",list);
        map.put("code",0);
        return map;
    }

    @PostMapping("/sections")
    public Map insert(@RequestBody Section section){
        Map map = new HashMap();
        try {
            sectionService.insertSection(section);
            map.put("msg","添加成功");
        }catch (Exception e){
            map.put("msg","添加失败");
        }
        return map;
    }

    @DeleteMapping("/sections/{sectionId}")
    public Map delete(@PathVariable("sectionId") Integer sectionId){
        Map map = new HashMap();
        try {
            sectionService.deleteById(sectionId);
            map.put("msg","删除成功");
        }catch (Exception e){
            map.put("msg","删除失败");
        }
        return map;
    }

    @DeleteMapping("/sections")
    public Map delete(@RequestBody Integer[] ids){
        Map map = new HashMap();
        System.out.println("ids = " + ids);
        try {
            sectionService.deleteSelect(ids);
            map.put("msg","删除成功");
        }catch (Exception e){
            map.put("msg","删除失败");
        }
        return map;
    }

    @PutMapping("/sections/{sectionId}")
    public Map update(@RequestBody Section section){
        Map map = new HashMap();
        try {
            sectionService.updateById(section);
            map.put("msg","更新成功");
        }catch (Exception e){
            map.put("msg","更新失败");
        }
        return map;
    }
}
